import axios from 'axios';
import dotenv from 'dotenv';
import { getTokenFromStore } from '../../auth/tokenStore.js';
import { getMyProject } from '../../auth/projectStore.js';
import mysql from 'mysql2/promise';

dotenv.config();

// 创建数据库连接池
const pool = mysql.createPool({
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 定义查询设备影子的函数
async function getDeviceShadow(deviceId) {
  try {
    // 先调用登录接口获取 Token
    const loginResponse = await axios.post('http://localhost:3000/login');
    if (!loginResponse.data.token) {
      throw new Error('Failed to retrieve token from login endpoint');
    }

    // 将获取到的 Token 存入 Store
    //setTokenToStore(loginResponse.data.token);

    // 获取缓存的 Token
    const token = getTokenFromStore();
    if (!token) {
      throw new Error('No valid token found');
    }

    // 获取项目 ID
    // const projectId = getMyProject();
    // if (!projectId) {
    //   throw new Error('No valid project ID found');
    // }

    // 定义请求的 URL
    const url = `https://9075152252.st1.iotda-app.cn-south-1.myhuaweicloud.com/v5/iot/67c6f14080c3872914af9de6/devices/67c6f14080c3872914af9de6_Smart_Home/shadow`;

    // 发送 GET 请求
    const response = await axios.get(url, {
      headers: {
        'X-Auth-Token': token,
        'Instance-Id': process.env.INSTANCE_ID,
        'Content-Type': 'application/json;charset=utf-8'
      }
    });

    // 提取 properties 部分
    const shadowData = response.data;
    const properties = shadowData.shadow[0]?.reported?.properties || {};

    // 将数据插入数据库
    await insertDeviceShadowData(deviceId, properties);

    // 返回提取的 properties 数据
    return properties;
  } catch (error) {
    console.error('Error fetching device shadow:', error.response ? error.response.data : error.message);
    throw error;
  }
}

// 定义允许更新的属性列表
const ALLOWED_PROPERTIES = [
  "smart_home_fan",
  "smart_home_light_Two",
  "smart_home_light_One",
  "smart_home_alarm",
  "smart_home_brightness",
  "Home_Temperature",
  "Home_Humidity",
  "Smoke"
];

// 修改: 插入或更新逻辑改为基于 (property_name, device_id) 的主键
async function insertDeviceProperties(deviceId, properties) {
  const connection = await pool.getConnection();
  try {
    // 遍历 properties 对象，逐条插入或更新数据
    for (const [key, value] of Object.entries(properties)) {
      // 只处理 ALLOWED_PROPERTIES 中的属性
      if (ALLOWED_PROPERTIES.includes(key)) {
        await connection.query(
          'INSERT INTO device_properties (property_name, property_value, device_id) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE property_value = ?',  // 修改: 使用 ON DUPLICATE KEY UPDATE 更新逻辑
          [key, JSON.stringify(value), deviceId, JSON.stringify(value)]
        );
      }
    }

    // 修改: 清理超出10条记录的数据，基于 (property_name, device_id) 的主键
    await connection.query(`
      DELETE FROM device_properties 
      WHERE (property_name, device_id) NOT IN (
        SELECT property_name, device_id FROM (
          SELECT property_name, device_id FROM device_properties ORDER BY property_name DESC, device_id DESC LIMIT 8
        ) AS latest_records
      )
    `);
  } finally {
    connection.release();
  }
}

// 修改：在 insertDeviceShadowData 函数中调用 insertDeviceProperties
async function insertDeviceShadowData(deviceId, properties) {
  const connection = await pool.getConnection();
  try {
    // 插入到 device_shadow 表
    await connection.query(
      'INSERT INTO device_shadow (device_id, properties) VALUES (?, ?) ON DUPLICATE KEY UPDATE properties = ?',
      [deviceId, JSON.stringify(properties), JSON.stringify(properties)]
    );

    // 新增：插入到 device_properties 表
    await insertDeviceProperties(deviceId, properties);
  } finally {
    connection.release();
  }
}

// 定义定期更新设备影子数据的函数
function startDeviceShadowPolling(deviceId, callback) {
  let isPolling = true;

  const pollDeviceShadow = async () => {
    if (!isPolling) return;

    try {
      const shadowData = await getDeviceShadow(deviceId);
      callback(null, shadowData);

      // 修改: 使用 JSON.stringify 美化输出设备影子数据
      //console.log(`Device Shadow Data for Device ID ${deviceId}:`, JSON.stringify(shadowData, null, 2));
    } catch (error) {
      callback(error, null);
    }

    // 三秒钟后再次调用
    setTimeout(pollDeviceShadow, 3000);
  };

  // 启动第一次轮询
  pollDeviceShadow();

  // 返回一个函数用于停止轮询
  return () => {
    isPolling = false;
  };
}

export { getDeviceShadow, startDeviceShadowPolling };